package com.myCommunity.dao.impl;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.myCinema.dao.HibernateUtil;
import com.myCommunity.dao.UsersDao;
import com.myCommunity.entity.Users;

public class UsersDaoImpl implements UsersDao {

	public Users fetchUsers(String username, String password) {
		Session sess = null;
		try{
			String hql = "from Users where username = :username and password = :password ";
			sess = HibernateUtil.openSession();
			Query q = sess.createQuery(hql);
			q.setString("username", username);
			q.setString("password", password);
			return (Users) q.uniqueResult();
		}finally{
			sess.close();
		}
	}

	public static void main(String[] args) {
		new UsersDaoImpl().fetchUsers("tom", "123");
		Session sess = HibernateUtil.openSession();
		System.out.println("done");
	}

	public void add(Users user) {
		Session sess = null;
		try{
			sess= HibernateUtil.openSession();
			Transaction tx = sess.beginTransaction();
			sess.save(user);
			tx.commit();
		}finally{
			sess.close();
		}
		
	}

	public Users fetchUsername(String username) {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			String hql = "from Users where username = :username";
			Query query = sess.createQuery(hql);
			query.setString("username", username);
			return (Users) query.uniqueResult();
		}finally{
			sess.close();
		}
	}

	public void update(Users user) {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			Transaction tx = sess.beginTransaction();
			sess.update(user);
			tx.commit();
		}finally{
			sess.close();
		}
	}
}